#!/bin/bash -x
RESOURCE_DIR=${NODE_HOME}/${SERVICE_NAME}

if [ "$SYSAK_VERTION" == "" ]; then
    export SYSAK_VERTION=2.4.0-1
fi
if [ "$NODE_EXPORT_VERSION" == "" ]; then
    export NODE_EXPORT_VERSION=1.5.0
fi
if [ "$ARCH" == "" ]; then
    export ARCH=x86_64
fi

init_node_exporter() {
    ##设置node_exporter开机自动启动
    cat <<EOF >node_exporter.service
[Unit]
Description=SysOM Monitor Prometheus
Documentation=SysOM Monitor Prometheus
Wants=network-online.target
After=network-online.target

[Service]
ExecStart=${RESOURCE_DIR}/node_exporter/node_exporter
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF
    NODE_EXPORTER_PKG=$(ls node_exporter-*.tar.gz | awk -F".tar.gz" '{print $1}')
    NODE_EXPORTER_TAR=${NODE_EXPORTER_PKG}.tar.gz
    tar -zxvf ${NODE_EXPORTER_TAR}
    rm -rf ${RESOURCE_DIR}/node_exporter
    mkdir -p ${RESOURCE_DIR}
    echo 1 ${NODE_EXPORTER_PKG}
    mv ${NODE_EXPORTER_PKG} ${RESOURCE_DIR}/node_exporter
    echo 2 ${RESOURCE_DIR}/node_exporter
    mv node_exporter.service /usr/lib/systemd/system
    systemctl daemon-reload
    systemctl enable node_exporter
    systemctl start node_exporter
    ps -elf | grep "${RESOURCE_DIR}/node_exporter/node_exporter" | grep -v grep 1>/dev/null
    if [ $? -ne 0 ]; then
        exit 1
    fi

}

function version_gt() { test "$(printf '%s\n' "$@" | sort -V | head -n 1)" != "$1"; }

update_sysak_config() {
    # Override the default configuration
    mkdir -p /etc/sysak
    cp -f base.yaml /etc/sysak/base.yaml
    sed "/pushTo/,/host/s/host: \"localhost\"/host: \"$SERVER_LOCAL_IP\"/g" -i /etc/sysak/base.yaml
}

install_or_update_sysak() {
    SYSAK_PKG=$(ls sysak-*.rpm)
    yum install -y ${SYSAK_PKG}

    ###install sysak from local yum repo first###
    if [ $? -ne 0 ]; then
        yum install -y sysak
        if [ $? -ne 0 ]; then
            echo "sysak install failed"
            exit 1
        fi
    fi
}

init_sysak_monitor_service() {
    rpm -q --quiet dnf || yum install -y dnf
    rpm -qa | grep sysak
    if [ $? -eq 0 ]; then
        current_version=$(rpm -q sysak --queryformat "%{VERSION}-%{RELEASE}")
        if version_gt $SYSAK_VERTION $current_version; then
	    install_or_update_sysak
            echo "sysak version is too low, current upgrade to $SYSAK_VERTION"
        else
            update_sysak_config
            echo "sysak version is $current_version, no need to upgrade"
        fi
    else
	install_or_update_sysak
    fi

    update_sysak_config

    # Create the /var/sysom for sysak unity
    mkdir -p /var/sysom

    systemctl enable sysak && systemctl start sysak
}

init_raptor_profiling() {
    bash -x raptor_profiling_deploy.sh
}

main() {
    init_node_exporter
    init_sysak_monitor_service
    exit 0
}

main | tee node_init.log